package stdlib.util

import io.ktor.utils.io.core.*
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.async
import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.launch
import java.time.LocalTime
import java.util.stream.Stream
import kotlin.random.Random
import kotlin.streams.toList

fun main() {
    test()
    Thread.sleep(10000)
}

fun test() {
    CoroutineScope(Dispatchers.Default).launch {
        val channel = Channel<List<Int>> { }
        val send = async {
            val list = mutableListOf<Int>()
            Random(1).nextInt()
            listOf(1, 2, Random(System.currentTimeMillis()).nextInt(), 4, 5, 6, 7, 8).stream().toList().forEach {
                list.add(it)
                if (it % 3 == 0) {
                    println("send $list")
                    channel.send(list.toList())
                    list.clear()
                }
            }
            channel.close()
        }

        val receive = async {
            val iterator = channel.iterator()
            while (iterator.hasNext()) {
                println("receive ${iterator.next()}")
            }
        }

        send.await()
        receive.await()

        println("over")
    }
}

suspend fun testStream() {
    println("hello world")
    val builder = Stream.builder<Int>()
    var i = 0
    while (i < 10) {
        builder.add(i++)
    }

    builder.build().forEach {
        println(it)
    }

    val channel = Channel<Int>()
    builder.build().forEach {
        println("--> ${i}")
        val r = fun(i: Int) {
            CoroutineScope(Dispatchers.IO).launch {
                println("-> ${i}")
                channel.send(i)
            }
        }
        r(i)
    }

    while (!channel.isEmpty) {
        println(channel.receive())
    }
}